package org.onepiece.admin.component.kafka;

import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;

/**
 * Created by IntelliJ IDEA.
 *
 * @author zhujianke@gaodun.com
 * @since 2022/9/4 18:19
 */
@Slf4j
public abstract class AbstractKafkaComponent {

    protected KafkaTemplate<String, String> kafkaTemplate;

    public void send(String topic, String message) {
        try {
            ListenableFuture<SendResult<String, String>> sendKafkaResult = kafkaTemplate.send(topic, message);
            SendResult<String, String> sendResult = sendKafkaResult.get();
            log.warn("{}#send topic:{} message:{} result:{}", this.getClass().getSimpleName(), topic, message, sendResult);
        } catch (Exception e) {
            log.error("SystemError {}#send exception topic:{} message:{}", this.getClass().getSimpleName(), topic, message, e);
        }
    }

    public void send(String topic, String key, String message) {
        try {
            ListenableFuture<SendResult<String, String>> sendKafkaResult = kafkaTemplate.send(topic, key, message);
            SendResult<String, String> sendResult = sendKafkaResult.get();
            log.warn("{}#send topic:{} key:{} message:{} result:{}", this.getClass().getSimpleName(), topic, key, message, sendResult);
        } catch (Exception e) {
            log.error("SystemError {}#send exception topic:{} key:{} message:{}", this.getClass().getSimpleName(), topic, key, message, e);
        }
    }

    public void send(String topic, Integer partition, String key, String message) {
        try {
            ListenableFuture<SendResult<String, String>> sendKafkaResult = kafkaTemplate.send(topic, partition, key, message);
            SendResult<String, String> sendResult = sendKafkaResult.get();
            log.warn("{}#send topic:{} partition:{} key:{} message:{} result:{}", this.getClass().getSimpleName(), topic, partition, key, message, sendResult);
        } catch (Exception e) {
            log.error("SystemError {}#send exception topic:{} partition:{} key:{} message:{}", this.getClass().getSimpleName(), topic, partition, key, message, e);
        }
    }
}
